package com.example.partner.adapter.find;

import static android.content.ContentValues.TAG;
import static android.content.Context.MODE_PRIVATE;

import static androidx.core.content.ContentProviderCompat.requireContext;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.partner.R;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.domain.Post;
import com.example.partner.model.domain.PostComment;
import com.example.partner.model.request.PostCommentAddRequest;
import com.example.partner.model.vo.PostCommentVO;
import com.example.partner.service.PostService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {

    private List<PostCommentVO> commentList = new ArrayList<>();
    private List<PostCommentVO> allList = new ArrayList<>();
    private ReplyAdapter replyAdapter;
    private Context context;


    public CommentAdapter(Context context,List<PostCommentVO> commentList,List<PostCommentVO> allList) {
        this.commentList = commentList;
        this.allList = allList;
        this.context = context;
    }

    public void setData(List<PostCommentVO> comments,List<PostCommentVO> all){
        if (comments!=null){
//            commentList.clear();
            commentList.addAll(comments);
        }
        if (all!=null){
            allList = all;
        }
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment, parent, false);
        return new CommentViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CommentViewHolder holder, int position) {
        PostCommentVO comment = commentList.get(position);
        // Set data to views
        holder.textViewCommenterName.setText(comment.getUsername());
        holder.textViewCommentContent.setText(comment.getContent());
        // 设置布局管理器，这里使用 LinearLayoutManager，您也可以选择其他布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        holder.recyclerViewReplies.setLayoutManager(layoutManager);
        // 使用 Glide 加载头像
        Glide.with(context)
                .load(comment.getAvatarUrl())
                .apply(new RequestOptions().circleCrop())  // 如果需要显示为圆形头像
                .into(holder.imageViewCommenterAvatar);  // 替换成你的头像 ImageView
        holder.textViewReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showReplyDialog(comment);
            }
        });

        // Handle expand replies click event
        holder.textViewExpandReplies.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleRepliesVisibility(holder, comment.getUserId());
            }
        });
    }
    private void toggleRepliesVisibility(CommentViewHolder holder, long commentId) {
        int newVisibility = holder.recyclerViewReplies.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;
        holder.recyclerViewReplies.setVisibility(newVisibility);
        // Load and display replies when expanding
        if (newVisibility == View.VISIBLE) {
            loadRepliesForComment(commentId, holder.recyclerViewReplies);
        }
//        loadRepliesForComment(commentId, holder.recyclerViewReplies);
    }
    private void loadRepliesForComment(long commentId, RecyclerView recyclerViewReplies) {
        // Filter and display replies based on the comment ID
        List<PostCommentVO> replies = filterRepliesForComment(commentId);

        // Update the UI with the filtered replies
        if (!replies.isEmpty()) {
            recyclerViewReplies.setVisibility(View.VISIBLE);
            // Create an adapter for the nested RecyclerView
            ReplyAdapter replyAdapter = new ReplyAdapter(replies);
            recyclerViewReplies.setAdapter(replyAdapter);
            replyAdapter.notifyDataSetChanged();
        }
    }

    // Add a method to show a reply dialog
    private void showReplyDialog(PostCommentVO comment) {
        // Implement your logic to show a reply dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("回复评论");

        // 设置对话框内容为一个EditText，以便用户输入回复内容
        final EditText input = new EditText(context);
        builder.setView(input);

        // 设置对话框按钮
        builder.setPositiveButton("回复", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取用户输入的回复内容
                String replyContent = input.getText().toString();
                // 在这里执行回复评论的逻辑，可以将回复内容提交到服务器等
                PostCommentAddRequest postComment = new PostCommentAddRequest();
                postComment.setPostId(comment.getPostId());
                postComment.setContent(replyContent);
                postComment.setPid(comment.getUserId());
                SharedPreferences sharedPreferences = context.getSharedPreferences("CurrentUser", MODE_PRIVATE);
                Long userId = sharedPreferences.getLong("userId", -1);
                postComment.setUserId(userId);
                addComment(postComment);
                // 关闭对话框
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 关闭对话框
                dialog.cancel();
            }
        });

        builder.show();
    }


    private void addComment(PostCommentAddRequest postCommentAddRequest){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        Call<BaseResponse<Boolean>> call = postService.addPostComment(postCommentAddRequest);
        call.enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean> >call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful()) {
                    Boolean data = response.body().getData();
                    notifyDataSetChanged();
                } else {
                    // 处理错误情况
                    Log.d(TAG, "onResponse:fail");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean> >call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }
    private List<PostCommentVO> filterRepliesForComment(long parentCommentId) {
        // Filter the commentList to get replies for the given parentCommentId
        List<PostCommentVO> filteredReplies = new ArrayList<>();
        for (PostCommentVO comment : allList) {
            if (comment.getPid() == parentCommentId) {
                filteredReplies.add(comment);
            }
        }
        return filteredReplies;
    }

    @Override
    public int getItemCount() {
        if (commentList == null){
            return 0;
        }
        return commentList.size();
    }

    static class CommentViewHolder extends RecyclerView.ViewHolder {
        TextView textViewCommenterName;
        TextView textViewCommentContent;
        TextView textViewReply;
        TextView textViewExpandReplies;
        ImageView imageViewCommenterAvatar;
        RecyclerView recyclerViewReplies;

        CommentViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewCommenterName = itemView.findViewById(R.id.textViewCommenterName);
            textViewCommentContent = itemView.findViewById(R.id.textViewCommentContent);
            textViewReply = itemView.findViewById(R.id.textViewReply);
            textViewExpandReplies = itemView.findViewById(R.id.textViewExpandReplies);
            imageViewCommenterAvatar = itemView.findViewById(R.id.imageViewCommenterAvatar);
            recyclerViewReplies = itemView.findViewById(R.id.recyclerViewReplies);
        }
    }
}
